const cartList = {
  state: {
    cart: JSON.parse(localStorage.getItem('vuex'))?.cart || [], // 购物车数组
  },
  getters: {
    totalMoney (state) {
      return state.cart.reduce((result, prod) => {
        if (prod.checked) {
          result += prod.price * prod.num * 100
        }
        return result
      }, 0)
    },
    totalAmount (state) {
      return state.cart.reduce((result, prod) => result + prod.num, 0)
    },
  },

  mutations: {
    modifyAmount (state, payload) {
    //   console.log(payload.data)
    },
    // 加入购物车
    addToCart (state, payload) {
      /* 如果购物车中已存在当前选购的商品，则叠加修改数量即可 */
      console.log(payload)
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) { // 有
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.id === payload.id) {
            copy.num += payload.num // 叠加数量
          }
          return copy
        })
      } else { // 没有
        state.cart.push({
          ...payload,
          checked: true, // 是否选中，默认选中
        })
      }
    },
    remove (state, id) {
      console.log('成功删除')
      state.cart = state.cart.filter(prod => prod.id !== id)
    },
  },
  actions: {

  },

}
export default cartList
